import type { Router } from 'vue-router'
import { tokenUtil } from '@/utils/auth'
import useStore from '@/stores'

const whiteList = ['/login']
export function installRouterGuard(router: Router) {
  router.beforeEach((to, from, next) => {
    const token = tokenUtil.getToken()
    if (whiteList.includes(to.path)) {
      next()
      return
    }
    if (!token) {
      next('/login')
      return
    }
    const { user } = useStore()

    if (!user.userInfo.roles?.length) {
      user.getUserInfo().then(routeList => {
        routeList.forEach(route => {
          router.addRoute('layout', route)
        })
       next({ ...to, replace: true })
      })
    } else {
      next()
    }
  })
}
